/**
 * 日志的封装
 */
const logger = require("morgan");
const fileStreamRotator = require("file-stream-rotator");

// 格式化日志输出格式
function formatLog(tokens, req, res) {
  return [
    tokens.method(req, res),
    tokens.url(req, res),
    tokens.status(req, res),
    decodeURI(tokens.url(req, res)), // 获取get参数
    JSON.stringify(req.body),
    tokens.res(req, res, "content-length"),
    "-",
    tokens["response-time"](req, res),
    "ms",
  ].join(" ");
}

const accessLog = () => {
  //  所有日志
  const accessLogStream = fileStreamRotator.getStream({
    filename: "./log/access-%DATE%.log",
    frequency: "daily",
    verbose: false,
    date_format: "YYYYMMDD",
  });
  return logger(
    function (tokens, req, res) {
      return formatLog(tokens, req, res);
    },
    { stream: accessLogStream },
  );
};

const errorLog = () => {
  // 错误日志
  const accessLogStreamErr = fileStreamRotator.getStream({
    filename: "./log/access-err-%DATE%.log",
    frequency: "daily",
    verbose: false,
    date_format: "YYYYMMDD",
  });

  return logger(
    function (tokens, req, res) {
      return formatLog(tokens, req, res);
    },
    {
      stream: accessLogStreamErr,
      skip: function (req, res) {
        return res.statusCode < 400;
      },
    },
  );
};
// 导出代码
module.exports = { accessLog, errorLog, logger };
